<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>使用模板引擎生成三级菜单</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .menu{
            width: 200px;
            margin: 20px;
            background: rgb(93, 126, 158);
            color: white;
            text-align: center;
        }
        .title{
            font-size: 18px;
            background: #369;
            padding: 5px 0px;
        }
        .city>li{
            height: 20px;
            line-height: 20px;
            cursor: pointer;
            padding: 5px 0px;
            position: relative;
        }
        .city>li:hover .district{
            display: block;
        }
        .district{
            width: 200px;
            background: rgb(93, 126, 158);
            position: absolute;
            right: -200px;
            top: 0px;
            display: none;
        }
        .district>li{
            height: 20px;
            line-height: 20px;
            cursor: pointer;
            padding: 5px 0px;
        }
    </style>
</head>
<body>
    <div class="menu">
        <script id="template" type="text/html">
            {{each $data item}}
            <div class="province">
                <div class="title">{{item.name}}</div>
                {{each item.citys item2}}
                <ul class="city">
                    <li>{{item2.name}}
                        <ul class="district">
                            {{each item2.districts item3}}
                            <li>{{item3.name}}</li>
                            {{/each}}
                        </ul>
                    </li>
                </ul>
                {{/each}}
            </div>
            {{/each}}
        </script>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.js"></script>
    <script src="./js/artTemplate.js"></script>
    <script>
        $.get('./data/menu.json',data=>{
            //获取所有的省份
            let p = data.filter(r=>r.pid===0)
            //给省份添加城市
            p.forEach(r => {
                r.citys = data.filter(r2=>r2.pid===r.id)
                //给城市添加区县
                r.citys.forEach(r3=>{
                    r3.districts = data.filter(r4=>r4.pid===r3.id)
                })
            });
            
            //在页面中呈现数据
            $('.menu').append(template('template',p))
        })
    </script>
</body>
</html>